package com.shangguosha.console;

import com.shangguosha.game.GameContext;
import com.shangguosha.game.GameManager;
import com.shangguosha.model.Card;
import com.shangguosha.model.Character;
import com.shangguosha.model.cards.Kill;
import com.shangguosha.model.cards.Dodge;
import com.shangguosha.model.cards.Peach;
import com.shangguosha.model.characters.TestCharacter;
import com.shangguosha.model.enums.*;
import com.shangguosha.factory.CharacterFactory;
import com.shangguosha.factory.CardFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 控制台演示系统
 */
public class ConsoleDemo {
    private GameContext gameContext;
    private GameManager gameManager;
    private Scanner scanner;
    private boolean running;
    
    public ConsoleDemo() {
        this.gameContext = GameContext.getInstance();
        this.gameManager = new GameManager();
        this.scanner = new Scanner(System.in);
        this.running = true;
    }
    
    public static void main(String[] args) {
        ConsoleDemo demo = new ConsoleDemo();
        demo.run();
    }
    
    public void run() {
        System.out.println("=== 三国杀控制台演示系统 ===");
        System.out.println("欢迎来到三国杀游戏！");
        
        initializeGame();
        
        while (running && !gameContext.isGameEnded()) {
            showMainMenu();
            handleUserInput();
        }
        
        showGameResult();
        scanner.close();
    }
    
    private void initializeGame() {
        System.out.println("\n正在初始化游戏...");
        
        // 创建测试玩家
        List<Character> players = createTestPlayers();
//        gameContext.setPlayers(players);
        
        // 创建测试卡牌
        createTestCards();
        
        // 初始化游戏
        gameManager.startGame(players);
        
        System.out.println("游戏初始化完成！");
        System.out.println("玩家数量: " + players.size());
        System.out.println("当前玩家: " + gameContext.getCurrentPlayer().getName());
        System.out.println("当前阶段: " + gameContext.getCurrentPhase());
    }
    
    private List<Character> createTestPlayers() {
        List<Character> players = new ArrayList<>();
        
        // 使用角色工厂创建测试角色
        Character player1 = CharacterFactory.createCharacter("liubei", "player1");
        Character player2 = CharacterFactory.createCharacter("caocao", "player2");
        Character player3 = CharacterFactory.createCharacter("sunquan", "player3");
        
        if (player1 != null) players.add(player1);
        if (player2 != null) players.add(player2);
        if (player3 != null) players.add(player3);
        
        // 如果工厂创建失败，使用默认角色
        if (players.isEmpty()) {
            players.add(new TestCharacter("player1", "刘备", Kingdom.SHU, Gender.MALE, 4));
            players.add(new TestCharacter("player2", "曹操", Kingdom.WEI, Gender.MALE, 4));
            players.add(new TestCharacter("player3", "孙权", Kingdom.WU, Gender.MALE, 4));
        }
        
        return players;
    }
    
    private void createTestCards() {
        // 使用卡牌工厂创建测试牌库
        List<Card> drawPile = CardFactory.createTestDeck();
        gameContext.setDrawPile(drawPile);
        
        // 给每个玩家发手牌
        for (Character player : gameContext.getPlayers()) {
            for (int i = 0; i < 4; i++) {
                Card card = gameContext.drawCard();
                if (card != null) {
                    player.drawCard(card);
                }
            }
        }
    }
    
    private void showMainMenu() {
        System.out.println("\n" + repeatString("=", 50));
        System.out.println("当前游戏状态:");
        showGameStatus();
        System.out.println("\n请选择操作:");
        System.out.println("1. 查看当前玩家详细信息");
        System.out.println("2. 查看手牌");
        System.out.println("3. 使用卡牌");
        System.out.println("4. 进入下一阶段");
        System.out.println("5. 切换到下一玩家");
        System.out.println("6. 查看所有玩家状态");
        System.out.println("7. 自动运行一回合");
        System.out.println("8. 重置游戏");
        System.out.println("0. 退出游戏");
        System.out.print("请输入选择 (0-8): ");
    }
    
    private void showGameStatus() {
        Character currentPlayer = gameContext.getCurrentPlayer();
        System.out.println("当前玩家: " + currentPlayer.getName() + 
                          " [" + currentPlayer.getKingdom() + "] " +
                          "(" + currentPlayer.getCurrentHp() + "/" + currentPlayer.getMaxHp() + " HP)");
        System.out.println("当前阶段: " + gameContext.getCurrentPhase());
        System.out.println("手牌数量: " + currentPlayer.getHandCardCount());
        System.out.println("存活玩家: " + gameContext.getAlivePlayerCount() + "/" + gameContext.getPlayers().size());
    }
    
    private void handleUserInput() {
        try {
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符
            
            switch (choice) {
                case 1:
                    showCurrentPlayerDetails();
                    break;
                case 2:
                    showHandCards();
                    break;
                case 3:
                    useCard();
                    break;
                case 4:
                    nextPhase();
                    break;
                case 5:
                    nextPlayer();
                    break;
                case 6:
                    showAllPlayersStatus();
                    break;
                case 7:
                    autoRunTurn();
                    break;
                case 8:
                    resetGame();
                    break;
                case 0:
                    exitGame();
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        } catch (Exception e) {
            System.out.println("输入错误，请输入数字！");
            scanner.nextLine(); // 清除错误输入
        }
    }
    
    private void showCurrentPlayerDetails() {
        Character player = gameContext.getCurrentPlayer();
        System.out.println("\n=== 玩家详细信息 ===");
        System.out.println("姓名: " + player.getName());
        System.out.println("势力: " + player.getKingdom());
        System.out.println("性别: " + player.getGender());
        System.out.println("体力: " + player.getCurrentHp() + "/" + player.getMaxHp());
        System.out.println("状态: " + (player.isAlive() ? "存活" : "阵亡"));
        System.out.println("技能数量: " + player.getSkills().size());
        System.out.println("装备数量: " + player.getEquipments().size());
        
        if (player.isChained()) {
            System.out.println("状态: 横置");
        }
        if (player.isFlipped()) {
            System.out.println("状态: 翻面");
        }
    }
    
    private void showHandCards() {
        Character player = gameContext.getCurrentPlayer();
        List<Card> handCards = player.getHandCards();
        
        System.out.println("\n=== 手牌列表 ===");
        if (handCards.isEmpty()) {
            System.out.println("没有手牌");
            return;
        }
        
        for (int i = 0; i < handCards.size(); i++) {
            Card card = handCards.get(i);
            System.out.println((i + 1) + ". " + card.getFullName() + 
                              " - " + card.getDescription());
        }
    }
    
    private void useCard() {
        Character player = gameContext.getCurrentPlayer();
        List<Card> handCards = player.getHandCards();
        
        if (handCards.isEmpty()) {
            System.out.println("没有可用的手牌！");
            return;
        }
        
        showHandCards();
        System.out.print("请选择要使用的卡牌编号 (1-" + handCards.size() + "): ");
        
        try {
            int cardIndex = scanner.nextInt() - 1;
            scanner.nextLine();
            
            if (cardIndex >= 0 && cardIndex < handCards.size()) {
                Card selectedCard = handCards.get(cardIndex);
                
                // 选择目标
                Character target = selectTarget();
                
                if (selectedCard.canUse(player, target)) {
                    selectedCard.use(player, target);
                    player.discardCard(selectedCard);
                    System.out.println("成功使用卡牌: " + selectedCard.getName());
                } else {
                    System.out.println("无法使用该卡牌！");
                }
            } else {
                System.out.println("无效的卡牌编号！");
            }
        } catch (Exception e) {
            System.out.println("输入错误！");
            scanner.nextLine();
        }
    }
    
    private Character selectTarget() {
        List<Character> alivePlayers = gameContext.getAlivePlayers();
        
        System.out.println("\n=== 选择目标 ===");
        for (int i = 0; i < alivePlayers.size(); i++) {
            Character player = alivePlayers.get(i);
            System.out.println((i + 1) + ". " + player.getName() + 
                              " [" + player.getCurrentHp() + "/" + player.getMaxHp() + " HP]");
        }
        
        System.out.print("请选择目标编号 (1-" + alivePlayers.size() + "): ");
        
        try {
            int targetIndex = scanner.nextInt() - 1;
            scanner.nextLine();
            
            if (targetIndex >= 0 && targetIndex < alivePlayers.size()) {
                return alivePlayers.get(targetIndex);
            }
        } catch (Exception e) {
            scanner.nextLine();
        }
        
        System.out.println("无效选择，默认选择自己");
        return gameContext.getCurrentPlayer();
    }
    
    private void nextPhase() {
        gameManager.nextPhase();
        System.out.println("进入下一阶段: " + gameContext.getCurrentPhase());
    }
    
    private void nextPlayer() {
        gameManager.nextPlayer();
        System.out.println("切换到下一玩家: " + gameContext.getCurrentPlayer().getName());
    }
    
    private void showAllPlayersStatus() {
        System.out.println("\n=== 所有玩家状态 ===");
        List<Character> players = gameContext.getPlayers();
        
        for (int i = 0; i < players.size(); i++) {
            Character player = players.get(i);
            String status = player.isAlive() ? "存活" : "阵亡";
            String current = (player == gameContext.getCurrentPlayer()) ? " [当前]" : "";
            
            System.out.println((i + 1) + ". " + player.getName() + 
                              " [" + player.getKingdom() + "] " +
                              "(" + player.getCurrentHp() + "/" + player.getMaxHp() + " HP) " +
                              status + current);
        }
    }
    
    private void autoRunTurn() {
        System.out.println("\n=== 自动运行回合 ===");
        Character currentPlayer = gameContext.getCurrentPlayer();
        System.out.println("为 " + currentPlayer.getName() + " 自动运行回合...");
        
        // 自动执行各个阶段
        GamePhase[] phases = {GamePhase.PREPARE, GamePhase.JUDGE, GamePhase.DRAW, 
                             GamePhase.PLAY, GamePhase.DISCARD, GamePhase.END};
        
        for (GamePhase phase : phases) {
            gameContext.setCurrentPhase(phase);
            System.out.println("执行阶段: " + phase);
            
            // 模拟阶段处理
            switch (phase) {
                case DRAW:
                    // 摸牌阶段
                    for (int i = 0; i < 2; i++) {
                        Card card = gameContext.drawCard();
                        if (card != null) {
                            currentPlayer.drawCard(card);
                        }
                    }
                    System.out.println("  摸了2张牌");
                    break;
                case PLAY:
                    // 出牌阶段 - 随机使用一张牌
                    if (!currentPlayer.getHandCards().isEmpty()) {
                        Card randomCard = currentPlayer.getHandCards().get(0);
                        System.out.println("  使用卡牌: " + randomCard.getName());
                        currentPlayer.discardCard(randomCard);
                    }
                    break;
                case DISCARD:
                    // 弃牌阶段 - 检查手牌上限
                    int handLimit = currentPlayer.getCurrentHp();
                    while (currentPlayer.getHandCardCount() > handLimit) {
                        Card cardToDiscard = currentPlayer.getHandCards().get(0);
                        currentPlayer.discardCard(cardToDiscard);
                        gameContext.discardCard(cardToDiscard);
                        System.out.println("  弃置卡牌: " + cardToDiscard.getName());
                    }
                    break;
            }
            
            try {
                Thread.sleep(500); // 暂停500ms以便观察
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        // 切换到下一玩家
        nextPlayer();
        System.out.println("回合结束，切换到: " + gameContext.getCurrentPlayer().getName());
    }
    
    private void resetGame() {
        System.out.println("\n重置游戏...");
        gameContext = GameContext.getInstance();
        gameManager = new GameManager();
        initializeGame();
        System.out.println("游戏已重置！");
    }
    
    private void exitGame() {
        System.out.println("\n感谢游玩三国杀！再见！");
        running = false;
    }
    
    private void showGameResult() {
        if (gameContext.isGameEnded()) {
            System.out.println("\n=== 游戏结束 ===");
            Character winner = gameContext.getWinner();
            if (winner != null) {
                System.out.println("获胜者: " + winner.getName() + " [" + winner.getKingdom() + "]");
            } else {
                System.out.println("游戏平局！");
            }
        }
    }
    
    /**
     * 重复字符串的辅助方法，兼容 Java 8
     */
    private String repeatString(String str, int count) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(str);
        }
        return sb.toString();
    }
}